<?php
namespace Pm\Controllers;

use Helpers\Main;
use Helpers\Tool;
use Helpers\Assets;
use Admin\Models\pm\XhpmTestCase;
use Admin\Models\pm\XhpmProduct;
use Modules\Power;

class TestcaseController extends ControllerBase
{
    private static $levels = [
        1 => '普通',
        2 => '重要',
        3 => '紧急',
    ];

    /**
     * 测试用例列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180716
     */
    public function indexAction()
    {
        if (!Power::exist('Bpm_Product_TestCase')) {
            return $this->sendViewError('权限不足', '无测试用例权限');
        }
        $iProductId = $this->request->getQuery('iProductId', 'int');
        if (!$iProductId) {
            return $this->sendViewError('请选择相关产品');
        }
        $this->di->get('assets')
            ->addCss('assets/sweetalert2/sweetalert2.min.css')
            ->addJs('assets/sweetalert2/sweetalert2.min.js');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        $this->view->pick('testcase/testCaseList');
        Assets::importJs('js/testcase/testCaseList.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        $this->view->setVars([
            'testCaseAdd'  => Power::exist('Bpm_Product_TestCase_Add'),
            'testCaseEdit' => Power::exist('Bpm_Product_TestCase_Edit'),
            'testCaseDel'  => Power::exist('Bpm_Product_TestCase_Del'),
            'levels'       => self::$levels,
            'iProductId'   => $iProductId,
        ]);
    }

    /**
    * 获取测试用例列表
    *
    * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
    *
    * create by zqk 20180716
    */
    public function getTestCaseAction()
    {
        try {
            if (!Power::exist('Bpm_Product_TestCase')) {
                return $this->sendErrorResponse(500, '无测试用例权限');
            }
            $iProductId = $this->request->getQuery('iProductId', 'int');
            $productObj = XhpmProduct::findFirst([
                'conditions' => "bDelete = 0 AND iId = $iProductId"
            ]);
            if (!$productObj) {
                return $this->sendErrorResponse(500, '请选择相关产品');
            }
            $condition = " bDelete = 0 AND iProductId = $iProductId";
            $builder = $this->modelsManager->createBuilder()
                ->addFrom('Admin\Models\pm\XhpmTestCase')
                ->where($condition)
                ->orderBy("iId desc");
            $data = Main::runBuilderPaginator($builder, true);
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());
        }
    }

    /**
     * 新建/编辑 测试用例表单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180716
     */
    public function testCaseFormAction()
    {
        $iId = $this->request->getQuery('iId', 'int');
        if ($iId) {
            if (!Power::exist('Bpm_Product_TestCase_Edit')) {
                return $this->sendViewError('权限不足', '无编辑测试用例权限');
            }
        } else {
            if (!Power::exist('Bpm_Product_TestCase_Add')) {
                return $this->sendViewError('权限不足', '无新增测试用例权限');
            }
        }
        $iProductId = $this->request->getQuery('iProductId', 'int');//项目Id
        Assets::easyUI();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/testcase/testCaseForm.js');
        $this->view->pick('testcase/testCaseForm');
        $this->view->setVars([
            'iId'    => $iId,
            'levels' => self::$levels,
            'iProductId' => $iProductId,
        ]);
    }

    /**
     * 新建/编辑测试用例
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180716
     */
    public function saveTestCaseAction()
    {
        $iId = $this->request->getPost('iId', 'int');
        //项目创建人id && name
        try {
            $this->db->begin();  //开启事务
            if ($iId) {
                if (!Power::exist('Bpm_Product_TestCase_Edit')) {
                    return $this->sendErrorResponse(500, '权限不足', '无编辑测试用例权限');
                }
                $testCase = XhpmTestCase::findFirst([
                    'conditions' => "bDelete = 0 AND iId = $iId"
                ]);
                if (!$testCase) {
                    return $this->sendErrorResponse(400, '参数错误！');
                }
            } else {
                if (!Power::exist('Bpm_Product_TestCase_Add')) {
                    return $this->sendErrorResponse(500, '权限不足', '无新增测试用例权限');
                }
                $testCase = new XhpmTestCase();
            }
            $testCase->assign($this->request->getPost());
            $result = $testCase->save();
            if (!$result) {
                $this->db->rollback();
                return $iId ? $this->sendErrorResponse(500, '操作失败') : $this->sendErrorResponse(500, '操作失败');
            }
            $this->db->commit();
            return $iId ? $this->sendSuccessResponse('操作成功') : $this->sendSuccessResponse('操作成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $iId ?
                $this->sendErrorResponse(500, '操作失败', $exception->getMessage()) :
                $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

    /**
     * 获取已存在的产品
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180625
     */
    public function getTestCaseInfoAction()
    {
        try {
            $iId = $this->request->getPost('iId', 'int');
            if (!$iId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XhpmTestCase::findFirst($iId);
            $data = $obj ? $obj->toArray() : [];
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取测试用例信息失败', $exception->getMessage());
        }
    }

    /**
     * 删除测试用例
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180716
     */
    public function delTestCaseByIdAction()
    {
        if (!Power::exist('Bpm_Product_TestCase_Del')) {
            return $this->sendErrorResponse(500, '权限不足', '无删除测试用例权限');
        }
        $iId = $this->request->getPost('iId', 'int');
        try {
            $testCaseObj = XhpmTestCase::findFirst([
                'conditions' => "bDelete = 0 AND iId = $iId"
            ]);
            if (!$testCaseObj) {
                return $this->sendErrorResponse(400, '参数错误');
            }
            $this->db->begin();
            $testCaseObj->bDelete = 1;
            $re = $testCaseObj->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除失败');
            }
            $this->db->commit();
            return $this-> sendSuccessResponse('删除成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

    /**
     * 检测产品合法性
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180717
     */
    public function checkProductByIdAction()
    {
//        $iProductId = $this->request->getPost('iProductId','int');
//        if (!$iProductId) {
//            return $this->sendErrorResponse(500,'请选择相关产品');
//        }
//        $productObj = XhpmProduct::findFirst([
//            'conditions' => "bDelete = 0 AND iId = $iProductId"
//        ]);
//        if (!$productObj) {
//            return $this->sendErrorResponse(500,'产品无效');
//        }
        return $this->sendSuccessResponse('验证成功');
    }

    /**
     * 导入测试用例模板form
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180726
     */
    public function importFormAction()
    {
        if (!Power::exist('Bpm_Product_TestCase_Add')) {
             return $this->sendViewError('权限不足', '无导入测试用例权限');
        }
        Assets::importMainJs('assets/jquery/jquery.form.js');
        Assets::importMainJs('assets/xh/xhExtra.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/testcase/importForm.js');
        $this->view->pick('testcase/importForm');
        $iProductId = $this->request->getQuery('iProductId', 'int');//项目Id
        $this->view->setVars([
            'iProductId' => $iProductId,
        ]);
    }

    /**
     * 导入测试用例模板
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180726
     * modify by zqk 20181102
     */
    public function importTestCaseAction()
    {
        if (!Power::exist('Bpm_Product_TestCase_Add')) {
            return $this->sendErrorResponse(500, '权限不足', '无导入测试用例权限');
        }
        $fileObj = $this->request->getUploadedFiles()[0];
        $productId = $this->request->getPost('iProductId');
        try {
            $datas = Tool::readExcel($fileObj->getTempName(), false, $fileObj->getExtension());
            $field = [
                '用例编号' => 'sCode',
                '功能模块' => 'sModule',
                '子模块' => 'sSubmodule',
                '功能点' => 'sFunctionPoint',
                '优先级别' => 'iLevel',
                '前置条件' => 'sPrecondition',
                '输入/操作步骤' => 'sSteps',
                '预期结果' => 'sExpectedResult',
                '实际结果（pass or fail）' => 'iActualResult',
                '缺陷编号' => 'sDefectNumber',
                '备注' => 'sRemarks',
            ];
            $levels = self::$levels;
            $columns = [];
            $this->db->begin();
            if (!empty($datas) && count($datas)>1) {
                foreach ($datas as $k => $v) {
                    if ($k == 0) {
                        foreach ($v as $key => $value) {
                            $columns[$key] = $field[$value];
                        }
                    } else {
                        $obj = new XhpmTestCase();
                        foreach ($v as $key => $value) {
                            $fieldName = $columns[$key];
                            if ($fieldName == 'iLevel') {
                                if (in_array($value, self::$levels)) {
                                    $reverse = array_flip($levels);
                                    $obj->$fieldName = $reverse[$value];
                                } else {
                                    $obj->$fieldName = 1;
                                }
                            } else {
                                $obj->$fieldName = $value;
                            }
                            $obj->iProductId = $productId;
                        }
                        $res = $obj->save();
                        if (!$res) {
                            $this->db->rollback();
                            return $this->sendErrorResponse('500', '导入失败');
                        }
                    }
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('导入成功');
        } catch (\Exception $e) {
            return $this->response->setContent($e->getMessage());
        }
    }


}

